﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace Registor2009
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            loadConfig();
            this.Icon = new Icon("Icon1.ico");
            notifyIcon1.Icon = new Icon("Icon1.ico");
        }

        private void lastInfoLog(string info)
        {
            tempInfo += DateTime.Now + ": " + info + System.Environment.NewLine;
            lastInfo.Text += tempInfo;
            tempInfo = "";
        }

        private void totalLog(string info)
        {
            allInfo.Text += DateTime.Now +": " + info + System.Environment.NewLine;
        }

        private void clearLastInfoLog()
        {
            lastInfo.Text = "";
        }

        private void newLine()
        {
            tempInfo += "=================================" + System.Environment.NewLine + System.Environment.NewLine;
        }
        
        /// <summary>
        /// 编码url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        protected string UrlEncode(string url)
        {
            byte[] bs = Encoding.GetEncoding("GB2312").GetBytes(url);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bs.Length; i++)
            {
                if (bs[i] < 128)
                    sb.Append((char)bs[i]);
                else
                {
                    sb.Append("%" + bs[i++].ToString("x").PadLeft(2, '0'));
                    sb.Append("%" + bs[i].ToString("x").PadLeft(2, '0'));
                }
            }
            return sb.ToString();
        }   

        private void label1_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 设置页面按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void configButtonClick(object sender, EventArgs e)
        {
            if (configForm == null)
            {
                configForm = new ConfigureForm(this);
            }
            configForm.Visible = true;
        }
        
        /// <summary>
        /// 加载配置信息
        /// </summary>
        public void loadConfig()
        {
            DataSet ds = new DataSet();
            ds.ReadXml("XMLFile1.xml");
            int tableCount = ds.Tables.Count;
            registorConfig.registorItems.Clear();
            for (int i = 1; i < tableCount; i++)
            {
                RegistorItem item = new RegistorItem();
                item.IsRegistorEnable = Boolean.Parse(ds.Tables[i].Rows[0].ItemArray[0].ToString());
                item.Description = ds.Tables[i].Rows[0].ItemArray[1].ToString();
                item.Hour = Int32.Parse(ds.Tables[i].Rows[0].ItemArray[2].ToString());
                item.Minute = Int32.Parse(ds.Tables[i].Rows[0].ItemArray[3].ToString());
                item.Random = Int32.Parse(ds.Tables[i].Rows[0].ItemArray[4].ToString());
                item.Flag = i;
                registorConfig.addItem(item);
            }
            string user = ds.Tables[0].Rows[0].ItemArray[0].ToString();
            string pwd = ds.Tables[0].Rows[0].ItemArray[1].ToString();
            userPwd.User = user;
            userPwd.Password = pwd;
                        
            DataSet dsDays = new DataSet();
            dsDays.ReadXml("RegistorDay.xml");
            daysConfig.Clear();
            daysConfig.Add(DayOfWeek.Monday, Boolean.Parse(dsDays.Tables[0].Rows[0].ItemArray[0].ToString()));
            daysConfig.Add(DayOfWeek.Tuesday, Boolean.Parse(dsDays.Tables[0].Rows[0].ItemArray[1].ToString()));
            daysConfig.Add(DayOfWeek.Wednesday, Boolean.Parse(dsDays.Tables[0].Rows[0].ItemArray[2].ToString()));
            daysConfig.Add(DayOfWeek.Thursday, Boolean.Parse(dsDays.Tables[0].Rows[0].ItemArray[3].ToString()));
            daysConfig.Add(DayOfWeek.Friday, Boolean.Parse(dsDays.Tables[0].Rows[0].ItemArray[4].ToString()));
            daysConfig.Add(DayOfWeek.Saturday, Boolean.Parse(dsDays.Tables[0].Rows[0].ItemArray[5].ToString()));
            daysConfig.Add(DayOfWeek.Sunday, Boolean.Parse(dsDays.Tables[0].Rows[0].ItemArray[6].ToString()));
        }

        public void checkRegistor()
        {
            clearLastInfoLog();
            bool needCheck = false;
            
            DateTime dt = DateTime.Now;
            
            if (daysConfig.Contains(new KeyValuePair<DayOfWeek, bool>(dt.DayOfWeek, false)))
            {
                lastInfoLog(dt.DayOfWeek+"不需要注册");
                return;
            }

            foreach(RegistorItem item in registorConfig.registorItems){
                if (item.IsRegistorEnable)
                {
                    DateTime temp = new DateTime(dt.Year,dt.Month,dt.Day,item.Hour,item.Minute,0);
                    //
                    if (dt.TimeOfDay.Subtract(temp.TimeOfDay) < new TimeSpan(0, 6, 0) && dt.TimeOfDay.Subtract(temp.TimeOfDay)>=new TimeSpan(0,0,0))
                    {
                        needCheck = true;
                        int second = item.Random * 60 - (int)dt.TimeOfDay.Subtract(temp.TimeOfDay).TotalSeconds;
                        if (second > 0)
                        {
                            Random random = new Random();
                            int randomSecond = random.Next(second);
                            lastInfoLog("随机等待 " + randomSecond + " 秒");

                            System.Threading.Thread.Sleep(randomSecond * 1000);
                        }
                        if (login(item))
                        {
                            registor(item);
                        }
                    }
                }
            }
            if (!needCheck)
            {
                lastInfoLog("当前时间不需要注册");
            }
        }

        private bool login(RegistorItem item)
        {
            string loginUrl = "http://222.191.237.170:8080/logincheck.php";
            string name = userPwd.User;//用户名
            string password = userPwd.Password;//密码
            string company = "北京中科方德公司";

            lastInfoLog("准备以账号 " + name + " 登陆系统 并注册 " + item.Description + "========================" + System.Environment.NewLine);
            //create postData
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "name=" + UrlEncode(name);
            postData += ("&password=" + password);
            postData += ("&company=" + UrlEncode(company));
            byte[] data = encoding.GetBytes(postData);

            // Prepare web request...
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(loginUrl);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            myRequest.CookieContainer = cookieContainer;
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            // Get response
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream());
            string content = reader.ReadToEnd();

            //Response.Write(content);
            if (content.Contains("attendance/welcome.php") && myResponse.StatusCode == HttpStatusCode.OK)
            {
                lastInfoLog("登陆系统成功");
                //postToText();
                return true;
            }
            else
            {
                lastInfoLog("登陆系统失败！！！ 错误原因:"+myResponse.StatusCode+","+myResponse.StatusDescription);
                newLine();
                //postToText();
                return false;
            }
        }

        private void registor(RegistorItem item)
        {
            string registorUrl = "http://222.191.237.170:8080/attendance/checksubmit.php?flag=" + item.Flag;

            //create postData
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "1=1";
            byte[] data = encoding.GetBytes(postData);

            // Prepare web request...
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(registorUrl);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            myRequest.CookieContainer = cookieContainer;
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            // Get response
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("gbk"));
            string content = reader.ReadToEnd();

            //Response.Write(content);
            if (content.Contains("welcome.php") && myResponse.StatusCode == HttpStatusCode.OK)
            {
                lastInfoLog("注册成功.");
                totalLog(item.Flag+"、"+item.Description + "注册成功.");
            }
            else
            {
                lastInfoLog("注册失败！！！错误原因:" + myResponse.StatusCode + "," + myResponse.StatusDescription);
                totalLog(item.Flag + "、" + item.Description + "注册失败！！！错误原因:" + myResponse.StatusCode + "," + myResponse.StatusDescription);
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            if (thread1 == null || !thread1.IsAlive)
            {
                thread1 = new System.Threading.Thread(this.checkRegistor);
                thread1.Start();
            }
        }

        private void start_Click(object sender, EventArgs e)
        {
            totalLog("已经开始运行注册程序...");
            if (thread1 == null || !thread1.IsAlive)
            {
                thread1 = new System.Threading.Thread(this.checkRegistor);
                thread1.Start();
            }
            timer1.Start();
            
            startMenu.Enabled = false;
            pauseMenu.Enabled = true;
        }

        private void pauseMenu_Click(object sender, EventArgs e)
        {
            if (thread1 != null && thread1.IsAlive)
            {
                thread1.Abort();
            }
            timer1.Stop();
            totalLog("已经暂停注册程序运行...");

            startMenu.Enabled = true;
            pauseMenu.Enabled = false;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (thread1 != null && thread1.IsAlive)
            {
                thread1.Abort();
                thread1 = null;
            }
            if (timer1 != null)
            {
                timer1.Stop();
                timer1.Dispose();
            }
        }

        /// <summary>
        /// 临时log信息
        /// </summary>
        private string tempInfo = "";
        /// <summary>
        /// 配置页面
        /// </summary>
        public ConfigureForm configForm;

        private CookieContainer cookieContainer = new CookieContainer();

        private UserPwd userPwd = new UserPwd();
        private RegistorConfig registorConfig = new RegistorConfig();
        private System.Threading.Thread thread1;
        private Dictionary<DayOfWeek, bool> daysConfig = new Dictionary<DayOfWeek, bool>();

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.notifyIcon1.Visible = false; 

        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Minimized;
                this.Visible = false;
                this.notifyIcon1.Visible = true;
            }
        }

        private void aboutMenu_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Author : Field.Kao \nEmail : soartju@gmail.com \nVersion : 我爱省时间 V0.1 beta1\t","关于",MessageBoxButtons.OK);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            allInfo.Text = "";
        }


    }
}
